package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryShopTypeList() {
        //1 从redis中查询缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOPTYPE_KEY);
        if (StrUtil.isNotBlank(shopTypeJson)) {
            //2 存在，直接返回结果
            return Result.ok(JSONUtil.toList(shopTypeJson, ShopType.class));
        }
        //判断命中的是否是空值
        if (shopTypeJson != null) {
            return Result.fail("查询不到店铺类型数据");
        }
        //3 不存在，查询数据库
        List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();
        if (shopTypeList.size() == 0 || shopTypeList == null) {
            //4 数据不存在，将空值写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOPTYPE_KEY, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 报错返回
            return Result.fail("查询不到店铺类型数据");
        }
        //5 存在，先写入redis缓存中 设置过期时间
        stringRedisTemplate.opsForValue().set(CACHE_SHOPTYPE_KEY, JSONUtil.toJsonStr(shopTypeList), CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
        //6 再返回给客户端
        return Result.ok(shopTypeList);
    }
}
